package org.bookie.jetty;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.start.Main;
import org.subethamail.smtp.MessageListener;
import org.subethamail.smtp.TooMuchDataException;
import org.subethamail.smtp.server.SMTPServer;

/**
 * Starts the Jetty Plus with JNDI and JMX
 * 
 * @author zubairov
 *
 */
public class Starter implements MessageListener {

	private static Log log = LogFactory.getLog(Starter.class);
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		List listeners = new ArrayList();
		listeners.add(new Starter());
		SMTPServer server = new SMTPServer(listeners);
		server.start();
		log.info("SMTPServer started");
		// Disable caching in Tapestry
		System.setProperty("org.apache.tapestry.disable-caching", "true");
		Main.main(new String[] { "./src/conf/jetty.xml", "./src/conf/jetty-plus.xml", "./src/conf/jetty-jmx.xml"});
	}

	public boolean accept(String arg0, String arg1) {
		log.info("Accepting mail from '" + arg0 + "' to '" + arg1 + "'");
		return true;
	}

	public void deliver(String from, String to, InputStream stream) throws TooMuchDataException, IOException {
		log.info("Recived from '" + from + "' to '" + to + "'");
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		String line = reader.readLine();
		while(line != null) {
			log.info("***********  " + line);
			line = reader.readLine();
		}
	}
	
}
